import './WeChatBind.scss'
import { v4 } from 'uuid'
import { useState } from 'react'
import { useMount } from 'ahooks'
import { Result, Button } from 'antd'

import { useRequest } from 'alova/client'
import { Http } from '../../Utils/Api'
import { GetIndexedDB, PutIndexedDB } from '../../Utils/IndexedDB'

const appid = 'wxa3d0c46c8bfcef89'
const redirect_uri = 'https://common-redirect.ljkjkf.com'

const WeChatBind = ({ Off }) => {
    const [uuid] = useState(v4())
    const [Loading, setLoading] = useState(true)
    const [BindState, setBindState] = useState(false)

    const { send } = useRequest(data => Http(data), { immediate: false })

    useMount(async () => {
        const user = await GetIndexedDB('user')
        const { unionId } = user
        const { client_Id } = await GetIndexedDB('config')

        setBindState(!!!unionId)
        setLoading(false)

        if (!unionId) {
            const state = `${uuid}@${appid}@${client_Id}`
            const get = `${sessionStorage.getItem('API')}/users/GetOpenUnionidOrTokenSSE?QRUuid=${uuid}&Type=unionid`
            const codeData = {
                self_redirect: true,
                id: 'QRcode',
                appid,
                scope: 'snsapi_login',
                response_type: 'code',
                redirect_uri: window.encodeURI(redirect_uri),
                state: state,
                style: 'black',
                href: 'https://image.ljkjkf.com/intellisiteSystem_TieKe/WebTemplate/code.css',
            }
            var eventSource = new EventSource(get)
            eventSource.onopen = () => new window.WxLogin(codeData)
            eventSource.onmessage = e => {
                const { data } = e
                if (data.length > 10) {
                    send({ method: 'post', url: 'users/BindOpenWeChatUnionIdAndUserId', params: { unionid: data } }).then(async () => {
                        eventSource.close()
                        user.unionId = data
                        await PutIndexedDB('user', user)
                        Off()
                    })
                }
            }
            eventSource.onerror = () => eventSource.close()
        }
    })

    const unBind = () => {
        send({ method: 'post', url: 'users/UnBindOpenWeChatUnionId' }).then(async () => {
            const user = await GetIndexedDB('user')
            user.unionId = ''
            await PutIndexedDB('user', user)
            Off()
        })
    }

    return (
        <div className="WeChatBindBox">
            {Loading ? ('加载中') : BindState ? (<div id="QRcode" />) :
                (
                    <Result
                        status="warning"
                        title="是否要解除微信与帐号的绑定?"
                        extra={<Button type="primary" key="console" danger onClick={unBind}>解除绑定</Button>}
                    />
                )}
        </div>
    )
};

export default WeChatBind;

